package com.github.caijh.mall.interceptor;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.github.caijh.mall.common.CommonResult;
import com.github.caijh.mall.system.service.SystemRoleService;
import org.springframework.web.servlet.HandlerInterceptor;


public class AdminAuthInterceptor implements HandlerInterceptor {

    @Inject
    private SystemRoleService systemRoleService;

    @Override
    public boolean preHandle(@Nonnull HttpServletRequest request, HttpServletResponse response, @Nullable Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String uri = request.getRequestURI();
        if (uri == null || uri.isEmpty()) {
            response.getWriter().write(JSON.toJSONString(CommonResult.forbidden()));
            return false;
        }

        boolean pass = systemRoleService.checkAuth(uri);

        if (!pass) {
            response.getWriter().write(JSON.toJSONString(CommonResult.forbidden()));
            return false;
        }
        return true;
    }

}
